package wili.attrMapping.core;

import java.util.ArrayList;
import java.util.List;

import wili.a.Refs;
import wili.attrMapping._user.b1.AttConst;
import wili.attrMapping._user.b1.AttMapingRule_main;
import wili.c.Ca;

/**
 * 属性集：
 * 
 * @author weilai2@163.com2@163.com
 */
public abstract class AttsObj extends Atts implements AttConst {// 属性集、映射目标、原对象、值类型解析、键名、键值

	public void updateNewAtts(String mapingToValue) {
		if (Refs.fm()) {

		}
		Ca.asert(!this.isNewAtts, "");
		List<Atts> newList = this.findNewAttsList();
		AttMapingRule_main.newNum++;
		Atts newAtts = newList.get(0);
		{
			String oldValue = newAtts.value;
			String fname = newAtts.file.file().getName();
			if (oldValue == null || !oldValue.replaceAll("\\s+", "").equals(mapingToValue.replaceAll("\\s+", ""))) {
				if (oldValue == null)
					Ca.pause();
				else
					Ca.pause();
				{
					++Att9.updateTimes;
					String st = "\n" + Att9.updateTimes + "," + fname + ", guid: " + newAtts.key;
					Att9.log7(st);
				}
				// AttCom.log23(" " + AttConst.msg("_afterUpdate: ") + mapingToValue);
				// AttCom.log23(" " + AttConst.msg("beforeUpdate: ") + oldValue);
				Att9.log7(" ", Bugs.afterUpdate, mapingToValue);
				Att9.log7(" ", Bugs.beforeUpdate, oldValue);
				AttMapingRule_main.bugNum++;
			}
			/*
			 * {=#DEFALUT_EDITABLE# && (['15','23'].includes(${ObjType}) &&
			 * [undefined,null].includes(${/DocEntry}) || ['17'].includes(${ObjType}))}
			 * {=#DEFALUT_EDITABLE# && (['15','23'].includes(${ObjType}) &&
			 * [undefined,null].includes(${/DocEntry}) ||
			 * ['17','540000006'].includes(${ObjType}))}
			 */
		}
		for (Atts atts : newList) {
			if (atts.list == null) {
				atts.file.getUpdateTimes()[0]++;
				atts.updateValue(mapingToValue);
				continue;
			}
			Ca.asert(list.size() > 0, "");
			for (Att att : atts.list) {
				att.setValue(this.mapingToValue);// todo....
				atts.file.getUpdateTimes()[0]++;
			}
		}
	}

	public String toString() {
		String st = list == null ? "value=" + value : list.toString();
		return "i" + id + "," + objName + ", " + st;
	}

	public AttsObj(AttsDefine def, AttsFile afile, String key, Object obj, boolean isNew) {
		super(def, afile, key, obj, isNew);
		Ca.asert(!Refs.useAttsBean(), "");
	}

	public Att att(String name) {
		for (Att at : list) {
			if (at.name.equals(name))
				return at;
		}
		return null;
	}

	public Att att(int ind) {
		if (ind < 0)
			ind = list.size() + ind;
		return list.get(ind);
	}

	public final List<Atts> findNewAttsList() {
		List<Atts> ret = conf.findNewAttsList(this);
		return ret;
	}

	public void setNewAttsList(List<Atts> lis) {
		this.newAttsList = lis;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public void addNewAtt(Atts atts) {
		if (this.newAttsList == null)
			newAttsList = new ArrayList<>();
		newAttsList.add(atts);
	}

	public ValueMapingNode getRuleTarget(ValueMapingNode root) {
		ValueMapingNode ret = root.addOrMergeAtts(this, false);
		return ret;
	}

}
